import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vehicle_management/pages/my_task_page/traisitEnd.dart';
import 'package:vehicle_management/pages/my_task_page/tranisitIng.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:vehicle_management/config/Config.dart';
import 'package:vehicle_management/public.dart';

// ignore: must_be_immutable
class TaskPage extends StatefulWidget {
  TaskPage() {
    // ignore: unnecessary_brace_in_string_interps
  }

  @override
  State<StatefulWidget> createState() {
    return new TaskPageState();
  }
}

class TaskPageState extends State<TaskPage>
    with SingleTickerProviderStateMixin {
  TabController _tabController;
  bool toggle = true;
  String _appKey;

  TaskPageState() {
    _appKey = preferences.getString("appKey");
  }

  ///运输结束数据
  List _trainsitEndlist = [];

  ///运输开始数据
  List _trainsitInglist = [];
  int _page = 1;
  int _endpage = 1;
  ScrollController _scrollControllerTrainsitEnd = new ScrollController(); //上拉加载
  ScrollController _scrollControllerTrainsitIng = new ScrollController(); //上拉加载
  // ignore: unused_field
  bool _transitingHasMore = true;
  bool hasMore = true;
  // ignore: unused_field
  int _transitIngCount = 0;
  int _transitEndCount = 0;

  /// 运输中数据
  @override
  void dispose() {
    _tabController.dispose();
    _scrollControllerTrainsitIng.dispose();
    _scrollControllerTrainsitEnd.dispose();
    super.dispose();
  }

  void initState() {
    super.initState();
    _tabController = new TabController(vsync: this, length: 2);
    this._getDataTransitEnd();
    this._getDataTransitIng();

    /// 监听滚动事件
    _scrollControllerTrainsitEnd.addListener(() {
      if (_scrollControllerTrainsitEnd.position.pixels ==
          _scrollControllerTrainsitEnd.position.maxScrollExtent) {
        this._getDataTransitEnd();
      }
    });
    _scrollControllerTrainsitIng.addListener(() {
      if (_scrollControllerTrainsitIng.position.pixels ==
          _scrollControllerTrainsitIng.position.maxScrollExtent) {
        this._getDataTransitIng();
      }
    });
  }

  ///获取运输结束的列表
  _getDataTransitEnd() async {
    if (this.hasMore) {
      var apiUrl =
          "${Config.transitUrl}?page=$_endpage&limit=10&taskStatus=2&isDelete=0&appKey=$_appKey";
      var response = await Dio().get(apiUrl);
      this._transitEndCount = (response.data)['count'];
      var res = (response.data)['data'];
      setState(() {
        if (res != null) {
          this._trainsitEndlist.addAll(res);
        }
        this._endpage++;
      });

      ///判断是否是最后一页
      if (this._trainsitEndlist.length >= this._transitEndCount) {
        setState(() {
          this.hasMore = false;
        });
      }
    }
  }

  _getDataTransitIng() async {
    if (this._transitingHasMore) {
      var apiUrl =
          "${Config.transitUrl}?page=$_page&limit=10&taskStatus=1&isDelete=0&appKey=$_appKey";
      var response = await Dio().get(apiUrl);
      this._transitIngCount = (response.data)['count'];
      var res = (response.data)['data'];
      setState(() {
        this._trainsitInglist.addAll(res);
        this._page++;
      });
      if (this._trainsitInglist.length >= this._transitIngCount) {
        setState(() {
          this._transitingHasMore = false;
        });
      }
    }
  }

  Widget _noData() {
    return Container(
      child: Column(
        children: <Widget>[
          Image.asset(
            'images/no_data.jpeg',
            fit: BoxFit.cover,
            width: 750,
            height: 500,
          ),
        ],
      ),
    );
  }

//设置运输中数据
  Widget _transittingListData(context, index) {
    return _transitingListItem(context, index);
  }

  //运输中列表的item
  // ignore: missing_return
  Widget _transitingListItem(context, index) {
    return tranisitIng(this._trainsitInglist, index, this._transitingHasMore,
        context, this._appKey);
  }

  // 运输结束列表
  Widget _transitEndListData(context, index) {
    return _transitEndListItem(context, index);
  }

  //运输结束列表的item
  _transitEndListItem(context, index) {
    return traisitEnd(this._trainsitEndlist, index, this.hasMore, context);
  }

  ///运输结束的下拉刷新
  Future<void> _onRefreshTransitEnd() async {
    await Future.delayed(Duration(milliseconds: 2000), () {
      print("刷新  结束列表》》");
      _getDataTransitEnd();
    });
  }

  ///运输中的下拉刷新
  Future<void> _onRefreshTransitIng() async {
    await Future.delayed(Duration(milliseconds: 2000), () {
      print("刷新 运输中列表》》");
      _getDataTransitIng();
    });
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);
    _tabController.addListener(() {
      //切换
      if (this._tabController.index == 0) {
        print(this._tabController.toString());
        print(this._tabController.index);
        print(this._tabController.previousIndex);
        print("刷新 运输中列表");
        _onRefreshTransitIng();
      } else {
        print(this._tabController.toString());
        print(this._tabController.index);
        print(this._tabController.previousIndex);
        print("刷新  结束列表");
        _onRefreshTransitEnd();
      }
    });
    return Scaffold(
      appBar: AppBar(
        centerTitle: true, // 标题居中
        title: Text('任务'),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.exit_to_app),
            onPressed: () {
              Navigator.pushReplacementNamed(context, '/');
            },
          ),
        ],
        bottom: PreferredSize(
          preferredSize: Size.fromHeight(48),
          child: Material(
            color: Colors.white,
            child: TabBar(
                controller: _tabController,
                indicatorSize: TabBarIndicatorSize.label,
                indicatorColor: Color(0xffFB5858),
                unselectedLabelColor: Color(0xff696969),
                labelColor: Color(0xffFB5858),
                labelStyle: TextStyle(fontSize: ScreenUtil().setSp(36)),
                tabs: <Widget>[
                  Tab(
                    // icon:  Icon(Icons.directions_bike),
                    text: '运输中',
                  ),
                  Tab(text: '运输结束'),
                ]),
          ),
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        children: <Widget>[
          ///运输中
          RefreshIndicator(
            child: this._trainsitInglist.length == 0
                ? this._noData()
                : ListView.builder(
                    controller: _scrollControllerTrainsitIng,
                    itemCount: this._trainsitInglist.length,
                    itemBuilder: this._transittingListData),
            onRefresh: _onRefreshTransitIng,
          ),

          ///运输结束
          RefreshIndicator(
            child: this._trainsitEndlist.length == 0
                ? this._noData()
                : ListView.builder(
                    controller: _scrollControllerTrainsitEnd,
                    itemCount: this._trainsitEndlist.length,
                    itemBuilder: this._transitEndListData),
            onRefresh: _onRefreshTransitEnd,
          ),
        ],
      ),
    );
  }
}
